<template>
  <div>
    <h v-if="loading">loading</h>
    <h2 v-if="errorMsg">{{ errorMsg }}</h2>
    <div class="row">
      <div class="card" v-for="(item, index) in users" :key="index">
        <a :href="item.url" target="_blank">
          <img :src="item.avatar_url" style="width: 100px" />
        </a>
        <p class="card-text">{{ item.name }}</p>
      </div>
    </div>
  </div>
</template>

<script>
import PubSub from 'pubsub-js'
import axios from 'axios'

export default {
  data () {
    return {
      loading: false,
      users: null,
      errorMsg: ''
    }
  },
  mounted () {
    // 订阅搜索的消息
    PubSub.subscribe('search', (msg, searchName) => {
      const url = `https://api.github.com/search/users?q=${searchName}`
      this.loading = true
      this.errorMsg = ''
      this.users = null
      axios.get(url)
        .then(response => {
          this.loading = false
          const result = response.data.items.map(item => {
            return {
              name: item.login,
              avatar_url: item.avatar_url,
              url: item.html_url
            }
          })
          this.users = result
        }).catch(() => {
          this.loading = false
          this.errorMsg = '请求失败'
        })
    })
  }
}
</script>

<style scoped>
.card {
  float: left;
  width: 33.333%;
  padding: 0.75rem;
  margin-bottom: 2rem;
  border: 1px solid #efefef;
  text-align: center;
}

.card > img {
  margin-bottom: 0.75rem;
  border-radius: 100px;
}

.card-text {
  font-size: 85%;
}
</style>
